#!/bin/sh

PREREQ=""
prereqs()
{
	echo "$PREREQ"
}
case $1 in
# get pre-requisites
prereqs)
	prereqs
	exit 0
	;;
esac

# print production information
PROD_DATE="2025/08/01"
PROD_VERSION="v1.0.0"
printf "\nStart Automated Production...\n"
echo "###################################"
echo "#   Automated Production System    "
echo "#   Version: ${PROD_VERSION}       "
echo "#   Date:${PROD_DATE}              "
echo "###################################"

# Load and configure network interfaces 
configure_network()
{
	echo "Configuring network interfaces..."
	# Load network script
	. /scripts/network
}

# Download system edisk
download_sys_edisk()
{
	# Prompt for file server IP address
	read -p "Enter file server ip address: " file_server
    while true; do
        if validate_ipv4 "$file_server"; then
			break
        else
			read -p "Invalid input, Re-Input file server ip address: " file_server
        fi
    done

	ping -c 3 "$file_server" || {
		echo "Please check your network connection and try again."
		prepare_install
	}

	ROOTFS_URL="http://$file_server/rootfs.tar.gz"
	
	# tmp directory
	if [ ! -d ${TMP_DIR} ]; then
		mkdir -p ${TMP_DIR} 
	fi

	# Download with 3 retries
	wget -O "$TAR_FILE" "$ROOTFS_URL" || {
		echo "System edisk download failed!"
		download_sys_edisk
	}

	# Verify downloaded file
	if [ ! -f "$TAR_FILE" ]; then
		echo "Downloaded file not found!"
		download_sys_edisk
	fi
}

prepare_install()
{
	# Load and configure network interfaces
	configure_network
	# configure network interfaces sleep 2 seconds
	sleep 2
	# Download system edisk
	download_sys_edisk
}

# CPU architecture, Debian version, and mirror
# ARCH="amd64"、ARCH="arm64"
ARCH="amd64"
# kernel version
KERNEL_VERSION="6.1.0-35-${ARCH}"
ROOTFS_VERSION="1.0.0-${ARCH}"

# download and extract rootfs
TMP_DIR="/tmp"
TAR_FILE="${TMP_DIR}/rootfs-${ROOTFS_VERSION}.tar.gz"

# Prepare installation environment
prepare_install

# =============================================
# Analyzing disk layout
# =============================================
echo "Analyzing disk layout..."
TARGET_DISK="/dev/sda"
BOOT_PART="${TARGET_DISK}1"
ROOT_PART="${TARGET_DISK}2"

# =============================================
# Create root partition
# =============================================
echo "Creating root partition..."
# Create root partition 
# boot partition size is 128MB
# root partition is starting from 128MB to the end of the disk
parted -s "$TARGET_DISK" mkpart primary ext4 128MiB 100%

# mkfs for root partition
mkfs.ext4 -F "$ROOT_PART"

# Display partition table
echo "Partition Table:"
parted -s "$TARGET_DISK" print

# =============================================
# Install System
# =============================================
echo "Installing system..."
# Unmount boot partition beause system default mount boot partition(/dev/sda1) to initramfs system /root directory
echo "unmounting boot partition..."
umount "$BOOT_PART" || true
# Create mount point for root partition
MNT_ROOT="/root"
# Create mount point root
if [ ! -d "$MNT_ROOT" ]; then
	mkdir -p "$MNT_ROOT"
fi
# Mount root partition
echo "Mounting root partition..."
mount "$ROOT_PART" "$MNT_ROOT"

echo "Extracting RootFS..."
tar -xzf "$TAR_FILE" -C "$MNT_ROOT"

# Create mount point for boot partition
MNT_BOOT="/boot"
# Create mount point boot
if [ ! -d "$MNT_BOOT" ]; then
	mkdir -p "$MNT_BOOT"
fi
# Mount boot partition
echo "Mounting boot partition..."
mount "$BOOT_PART" "$MNT_BOOT"

# Copy kernel and initrd to boot partition
echo "Copying kernel and initrd to boot partition..."
cp -f "$MNT_ROOT/boot/vmlinuz-${KERNEL_VERSION}" "$MNT_BOOT"
cp -f "$MNT_ROOT/boot/initrd.img-${KERNEL_VERSION}" "$MNT_BOOT"
cp -f "$MNT_ROOT/boot/config-${KERNEL_VERSION}" "$MNT_BOOT"
cp -f "$MNT_ROOT/boot/System.map-${KERNEL_VERSION}" "$MNT_BOOT"
cp -f "$MNT_ROOT/boot/grub/grub.cfg" "$MNT_BOOT/grub"
# Remove old boot directory
echo "Removing old boot directory..."
if [ -d "$MNT_ROOT/boot" ]; then
	rm -rf "$MNT_ROOT/boot"
fi

# =============================================
# Post-Install Configuration
# =============================================
#echo "Configuring system..."
# Bind mount for chroot
#mount --bind /dev "$MNT_ROOT/dev"
#mount --bind /proc "$MNT_ROOT/proc"
#mount --bind /sys "$MNT_ROOT/sys"

# Basic system setup
chroot "$MNT_ROOT" /bin/bash <<EOF
# Fstab configuration
cat > /etc/fstab <<FSTAB_EOF
$(blkid -o export "$BOOT_PART" | grep ^UUID=) /boot ext4 defaults 0 2
$(blkid -o export "$ROOT_PART" | grep ^UUID=) /     ext4 defaults 0 1
FSTAB_EOF

EOF

# sync data write to disk
sync

# =============================================
# Cleanup
# =============================================
clean_up()
{
	# unmount partition
	echo "unmount partition..."
	umount -a -r
}

# Call clean up on exit
clean_up

echo "Install Custom Linux Complete..."
# Reboot System
echo "Rebooting System..."
/sbin/reboot -f
